package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //上传文件
    @PostMapping
    public AjaxResult upload(@RequestPart("file")MultipartFile file){
        try {
            //获取原始文件名
            String oName = file.getOriginalFilename(); // xxx.jpg
            String extName = oName.substring(oName.lastIndexOf(".") + 1);//jpg
            //上传成功之后返回的文件名
            String fileName = FastDfsUtils.upload(file.getBytes(), extName);
            //将文件名设置到AjaxResult并返回给前端
            return AjaxResult.me().setResultObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    //文件删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path")String path){
        try {
            String temPath = path.substring(1);
            //获取第一个/的位置
            int index = temPath.indexOf("/");
            String groupName = temPath.substring(0,index);
            String fileName = temPath.substring(index+1);
            FastDfsUtils.delete(groupName,fileName);
            //将文件名设置到AjaxResult并返回给前端
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
